<?php

namespace frontend\modules\business\controllers\user;

use common\models\business\BusinessPig;
use common\models\shop\ShopUserAddress;
use frontend\controllers\BaseMobileController;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;


/**
 * 仅仅为了兼容以前生成的二维码，做跳转用的
 */
class AddressController extends BaseMobileController
{

    /**
     * @return string
     * 地址管理
     */
    public function actionIndex()
    {

        $address = ShopUserAddress::find()
            ->select('*,county as area')
            ->where('userid=:userid',[':userid'=>$this->user['userid']])
            ->asArray()
            ->all();

        return $this->render('@template/mobile/address_list.html',[
            'address' => \GuzzleHttp\json_encode($address)
        ]);
    }



    /**
     * @return string
     * 处理地址数据
     */
    public function actionPostAddress()
    {
        $postdata = \Yii::$app->request->post();
        $data = [
            'province' => $postdata['province'],
            'city' => $postdata['city'],
            'county' => $postdata['area'],
            'address' => $postdata['address'],
            'tel' => $postdata['tel'],
            'userid' => $this->user['userid'],
            'name' => $postdata['name'],
        ];

        if (!empty($postdata['id'])) {
            $res = \Yii::$app->db->createCommand()->update(ShopUserAddress::tableName(),$data,'id=:id',[':id'=>$postdata['id']])->execute();
        } else {
            $res = \Yii::$app->db->createCommand()->insert(ShopUserAddress::tableName(),$data)->execute();
        }
        return $res?$this->jsonMsg():$this->jsonMsg('操作失败',1);

    }


    /**
     * @param $id
     * @return array
     * 设置为默认
     */
    public function actionSetdef($id)
    {
        \Yii::$app->db->createCommand()->update(ShopUserAddress::tableName(),['isdef'=>0],'userid=:uid',[':uid'=>$this->user['userid']])->execute();
        $res = \Yii::$app->db->createCommand()->update(ShopUserAddress::tableName(),['isdef'=>1],'id=:id',[':id'=>$id])->execute();

        return $res?$this->jsonMsg('设置为默认地址'):$this->jsonMsg('操作失败',1);
    }


    /**
     * @param $id
     * 删除
     */
    public function actionDelete($id)
    {
        $res = \Yii::$app->db->createCommand()->delete(ShopUserAddress::tableName(),'id=:id',[':id'=>$id])->execute();

        return $res?$this->jsonMsg():$this->jsonMsg('操作失败',1);
    }


    protected function findModel($id)
    {
        if (($model = ShopUserAddress::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}